﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ComputerResourceConsole.lib;
using ComputerResourceConsole.factory;
using ComputerResourceConsole.common;
using System.IO;
using System.Net;
using System.Diagnostics;

namespace ComputerResourceConsole.view
{
    public partial class frm_update : Form
    {
        private IConfig _pConfig = null;

        public frm_update()
        {
            InitializeComponent();
            this._pConfig = ComponentOperaFactory.createConfig();
            this._pConfig.loadConfig();
        }

        private void confirm_Click(object sender, EventArgs e)
        {
            //下载之前先做判断，判断是否已经启动了模型服务进程
            string processName = "container_node";
            Process proc = getProcess(processName);
            if (proc == null)
            {
                //下载文件，并显示进度条
                this.confirm.Enabled = false;
                this.Cancel.Enabled = false;
                this.progressBar1.Visible = true;
                this.splitContainer1.Panel2.Enabled = true;
                System.Windows.Forms.Application.DoEvents();

                string originPath = CommonMethod.getAppDirection() + this._pConfig.NodejsPath;
                //获取文件名
                string fileName = Path.GetFileName(originPath);

                //获取存储的上级目录
                DirectoryInfo info = new DirectoryInfo(originPath);
                string fileDirectory = info.Parent.FullName;

                string downloadUrl = this._pConfig.VersionCheckPath + "/downloadNewest";
                string filePath = fileDirectory + "\\temp\\" + "container_node.exe";
                bool status = DownloadFile(downloadUrl, filePath, this.progressBar1);
                //下载完成之后，替换文件
                if (status)
                {
                    CopyFileAndReplace(filePath, originPath);
                }        
            }
            else
            {
                MessageBox.Show("The Model Container is running! If you want to download the latest version, please close it in advance!", "System Attention", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }             
        }

        private void Cancel_Click(object sender, EventArgs e)
        {
            //直接关闭
            this.Close();
        }

        private bool DownloadFile(string url, string filePath, System.Windows.Forms.ProgressBar progress)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                long totalBytes = response.ContentLength;
                if (progress != null)
                {
                    progress.Maximum = (int)totalBytes;
                }

                if (CommonMethod.createFile(filePath))
                {
                    Stream st = response.GetResponseStream();
                    Stream so = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
                    long totalDownloadByte = 0;
                    byte[] by = new byte[1024];
                    int osize = st.Read(by, 0, 1024);
                    while (osize > 0)
                    {
                        totalDownloadByte = osize + totalDownloadByte;
                        so.Write(by, 0, osize);
                        progress.Value = (int)totalDownloadByte;
                        osize = st.Read(by, 0, 1024);
                        System.Windows.Forms.Application.DoEvents();
                    }
                    so.Close();
                    st.Close();
                    return true;

                }
                else
                {
                    MessageBox.Show("Some Error happen in downloading the files!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    this.confirm.Enabled = true;
                    this.Cancel.Enabled = true;
                    this.progressBar1.Visible = false;
                    this.splitContainer1.Panel2.Enabled = false;
                    return false;
                }

            }
            catch (Exception e)
            {
                MessageBox.Show("Some Error happen in downloading the files!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.confirm.Enabled = true;
                this.Cancel.Enabled = true;
                this.progressBar1.Visible = false;
                this.splitContainer1.Panel2.Enabled = false;
                return false;
            }
        }

        private Process getProcess(String name)
        {
            Process[] procs = Process.GetProcesses();
            for (int i = 0; i < procs.Length; i++)
            {
                if (procs[i].ProcessName == name)
                {
                    return procs[i];
                }
            }
            return null;
        }

        private void CopyFileAndReplace(string fromPath, String destPath)
        {
            File.Delete(destPath);
            File.Move(fromPath, destPath);
            MessageBox.Show("Update Application finished! Please start the Model container!", "Update Finish", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.Close();
        }
    }
}
